package com.Guo.system.controller;
import com.Guo.handler.BusinessException;
import com.Guo.response.Result;
import com.Guo.response.ResultCode;
import com.Guo.system.entity.User;
import com.Guo.system.mapper.UserMapper;
import com.Guo.system.service.UserService;
import com.Guo.system.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Guo
 * @since 2020-12-01
 */

@RestController
@RequestMapping("/user")
@Api(value = "用户管理")
public class UserController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据条件进行分页查询
     * @param current
     * @param size
     * @param userVO
     * @return
     */
     //@RequestBody以json数据接收
    @PostMapping("/findUserPage")
    @ApiOperation(value = "分页查询用户信息",notes = "分页查询用户信息")
    public Result findUserPage(@RequestParam(required = true,defaultValue = "1")Integer current,
                               @RequestParam(required = true,defaultValue = "6")Integer size,
                              @RequestBody UserVO userVO){
        //对用户进行分页,泛型中注入的就是用户实体类
        Page<User> page = new Page<>(current,size);
        Page<User> userPage = userService.findUserPage(page, userVO);
        return Result.ok().data("userPage",userPage);
    }

    /**
     * 根据条件进行分页查询
     * @param id
     * @return
     */
    //@RequestBody以json数据接收
    @PostMapping("/binding")
    @ApiOperation(value = "绑定用户信息",notes = "绑定用户信息")
    public Result binding(Long id){
        //对用户进行分页,泛型中注入的就是用户实体类
        System.out.println(id);
        User byId = userService.binding(id);
        if (byId==null){
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        return Result.ok().data("user",byId);
    }


    @PostMapping("/deleteUser")
    @ApiOperation(value = "删除用户信息",notes = "删除用户信息")
    public Result deleteUser(Integer id){
        System.out.println("删除的编号为："+id);
        boolean b = userService.removeById(id);
        if (!b){
            throw new BusinessException(ResultCode.DELETE_ERROR_EXCEPTION.getCode(),ResultCode.DELETE_ERROR_EXCEPTION.getMessage());
        }
        return Result.ok().data("answerUpdate",true);
    }

    @ApiOperation(value = "导出用户信息")
    @PostMapping(value = "/export")
    public void exportUserExcel(HttpServletResponse response, @RequestBody(required = false) UserVO userVO) throws IOException {
        QueryWrapper<User> wrapper = getWrapper(userVO);
        List<User> users = userService.list(wrapper);
        userService.exportUserExcel(response,users);
    }

    /**
     * 封装查询条件
     *
     * @param userVO
     * @return
     */
    private QueryWrapper<User> getWrapper(UserVO userVO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userVO != null) {
            if (!StringUtils.isEmpty(userVO.getDepartmentId())) {
                queryWrapper.eq("department_id", userVO.getDepartmentId());
            }
            if (!StringUtils.isEmpty(userVO.getUsername())) {
                queryWrapper.eq("username", userVO.getUsername());
            }
            if (!StringUtils.isEmpty(userVO.getEmail())) {
                queryWrapper.eq("email", userVO.getEmail());
            }
            if (!StringUtils.isEmpty(userVO.getSex())) {
                queryWrapper.eq("sex", userVO.getSex());
            }
            if (!StringUtils.isEmpty(userVO.getNickname())) {
                queryWrapper.eq("nickname", userVO.getNickname());
            }
        }
        return queryWrapper;
    }

    /**
     * 添加用户信息
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "编辑用户", notes = "编辑用户信息")
    @PostMapping("/userEdit")
    public Result userEdit(@RequestBody User user) {
        if(user.getId()!=null){
            //说明为修改用户
            User byId = userService.getById(user.getId());
            byId.setBirth(user.getBirth());
            byId.setNickname(user.getNickname());
            byId.setUsername(user.getUsername());
            byId.setPassword(passwordEncoder.encode(user.getPassword()));
            byId.setEmail(user.getEmail());
            byId.setDepartmentId(user.getDepartmentId());
            byId.setPhoneNumber(user.getPhoneNumber());
            byId.setSex(user.getSex());
            byId.setAvatar(user.getAvatar());
            int i = userMapper.updateById(byId);
            if (i!=1){
                throw new BusinessException(ResultCode.UPDATE_ERROR_EXCEPTION.getCode(),ResultCode.UPDATE_ERROR_EXCEPTION.getMessage());
            }
            return Result.ok().data("answer",true);
        }else{
            //为新增用户
            userService.addUser(user);
            System.out.println("用户详情："+user.toString());
            return Result.ok().data("answer",true);
        }
    }
    @ApiOperation(value = "修改用户状态")
    @PostMapping(value = "/updateStatus")
    public Result updateStatus(@RequestBody User user) {
        User byId = userService.getById(user.getId());
        if (byId.getStatus()==1){
            byId.setStatus(0);
        }else if(byId.getStatus()==0) {
            byId.setStatus(1);
        }
        int i = userMapper.updateById(byId);
        if (i>0){
            return Result.ok().data("answer",true);
        }else{
            return Result.ok().data("answer",false);
        }
    }
}

